#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "NoCopy.hpp"
#define SVR_PORT 8080
#define SVR_SOCKETFD -1
#define SIZE 1024

class UdpServer : public NoCopy
{
public:
    UdpServer(int port = SVR_PORT)
        : _port(port), _socketfd(SVR_SOCKETFD)
    {
    }
    ~UdpServer() 
    {
        close(_socketfd);
    }
    // 1. 创建套接字
    // 2. bind ip和端口
    // 3. 接受数据
    // 4. 发送数据
    // 5. 关闭套接字
    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        struct sockaddr_in myaddr;
        memset(&myaddr, 0, sizeof(myaddr));
        myaddr.sin_family = AF_INET;
        myaddr.sin_port = htons(_port);
        myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        if (bind(_socketfd, (struct sockaddr *)&myaddr, sizeof(myaddr)) == 0)
        {
            std::cout << "bind success! sockfd: " << _socketfd << std::endl;
        }
        else
        {
            std::cout << "bind failed!" << std::endl;
        }
    }
    void Start()
    {
        char buff[SIZE];
        while (true)
        {
            sockaddr_in clientaddr;
            socklen_t addrlen;
            int n = recvfrom(_socketfd, buff, sizeof(buff), 0, (struct sockaddr*)&clientaddr , &addrlen);
            if (n > 0)
            {
                buff[n] = 0;
                printf("client say: %s\n", buff);
                sendto(_socketfd, buff, sizeof(buff), 0,(struct sockaddr*)&clientaddr, sizeof(clientaddr));
            }
        }
    }

private:
    int _socketfd;
    uint16_t _port;
};